//
//  ZJPageContentView.m
//  ScrollPageView
//
//  Created by kepuna on 2017/4/12.
//  Copyright © 2017年 kepuna. All rights reserved.
//

#import "ZJPageContentView.h"

@interface ZJPageContentView ()<UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) NSArray *childControllers;
@property (nonatomic, weak) UIViewController *parentController;
@property (nonatomic, strong) UICollectionView *collectionView;
/// 开始拖拽滚动时的偏移量x
@property (nonatomic, assign) CGFloat startOffsetX;
@property (nonatomic, assign) BOOL isForbidDelegate; // 是否执行代理方法
@property (nonatomic, assign) NSInteger targetIndex;

@end 

static NSString *CollectionViewCellReuseIdentifier = @"CollectionViewCellReuseIdentifier";

@implementation ZJPageContentView

- (instancetype)initWithFrame:(CGRect)frame childControllers:(NSArray *)controllers parentController:(UIViewController *)parentController {
    if (self = [super initWithFrame:frame]) {
        self.childControllers = controllers;
        self.parentController = parentController;
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    // 把所有子控制器添加到父控制器中
    for (UIViewController *childVC in self.childControllers) {
        [self.parentController addChildViewController:childVC];
    }
    
    // 添加collectionView用于在cell中存放控制器的view
    [self addSubview:self.collectionView];
}

- (void)setCurrentIndex:(NSInteger)index {
    self.isForbidDelegate = YES;
    CGFloat offsetX = index * self.collectionView.bounds.size.width;
    [self.collectionView setContentOffset:CGPointMake(offsetX, 0) animated:NO];
}

- (UICollectionView *)collectionView {
    if (_collectionView == nil) {
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        flowLayout.itemSize = self.bounds.size;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        _collectionView = [[UICollectionView alloc]initWithFrame:self.bounds collectionViewLayout:flowLayout];
        _collectionView.showsVerticalScrollIndicator = NO;
        _collectionView.showsHorizontalScrollIndicator = NO;
        _collectionView.bounces = NO;
        _collectionView.pagingEnabled = YES;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        [_collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:CollectionViewCellReuseIdentifier];
    }
    return _collectionView;
}

#pragma mark -- UICollectionViewDataSource
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.childControllers.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:CollectionViewCellReuseIdentifier forIndexPath:indexPath];
    
    // 防止循环添加，先移除无用的
    for (UIView *view in cell.contentView.subviews) {
        [view removeFromSuperview];
    }
    
    UIViewController *childVC = nil;
    if (self.childControllers != nil && self.childControllers.count) {
        childVC = self.childControllers[indexPath.item];
        childVC.view.frame = cell.contentView.bounds;
        [cell.contentView addSubview:childVC.view];
    }
    return cell;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.isForbidDelegate = NO;
    self.startOffsetX = scrollView.contentOffset.x;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (self.isForbidDelegate) {
        return;
    }
    
    // 定义要获取的数据
    NSInteger sourceIndex = 0;
    NSInteger targetIndex = 0;
    
    // 判断是左滑还是右滑
    CGFloat currentOffsetX = scrollView.contentOffset.x;
    CGFloat scrollViewWidth = scrollView.bounds.size.width;
    if (currentOffsetX > self.startOffsetX) { // 左滑
        sourceIndex = (NSInteger)(currentOffsetX / scrollViewWidth);
        targetIndex = sourceIndex + 1;
        if (targetIndex >= self.childControllers.count) {
            targetIndex = self.childControllers.count - 1;
        }
        if (currentOffsetX - self.startOffsetX == scrollViewWidth) {
            targetIndex = sourceIndex;
        }
    } else { // 右滑
        targetIndex = (NSInteger)(currentOffsetX / scrollViewWidth);
        sourceIndex = targetIndex + 1;
        if (sourceIndex >= self.childControllers.count) {
            sourceIndex = self.childControllers.count - 1;
        }

    }
    self.targetIndex = targetIndex;
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if ([self.delegate respondsToSelector:@selector(pageContentView:targetIndex:)]) {
        [self.delegate pageContentView:self targetIndex:self.targetIndex];
    }
}

@end
